import { defineStore } from 'pinia';
import { ref } from 'vue';
import service from '../utils/service';
import { ElMessage } from "element-plus";


export const useCartStore = defineStore('cart', {
  state: () => ({
    cartList: [],
    totalQuantity: 0,
    totalPrice: 0,
  }),
  actions: {
    //获取用户购物车
    async getCartList(userId) {
      try {
        const res = await service.get(`/cart-goods/cart-goods-list/${userId}`);
        this.cartList = res.data;
        this.updateCartSummary();
      } catch (error) {
        console.error('Failed to get cartList:', error);
      }
    },

    //新增商品
    async addToCart(goods) {
      try {
        const res = await service.post(`/cart-goods/add`, goods)
        this.getCartList(goods.userId)
        if (res.code === 200) {
          ElMessage({
            message: '已添加进购物车',
            type: 'success'
          })
        }
      } catch (error) {
        console.error('Failed to add goods to cartList:', error);
      }
    },

    //修改购物车商品数量
    async updateQuantity(goods) {
      var data = ref({
        cgId: goods.cgId,
        cgNum: goods.cgNum,
        cgPrice: goods.cgPrice,
        goodsSpecsId: goods.goodsSpecsId,
        userId: goods.userId
      })
      try {
        const res = await service.put(`/cart-goods/update`, data.value)
        console.log(res);
        this.updateCartSummary();
      } catch (error) {
        console.error('Failed to update cartGoodsNum:', error);
      }
    },

    //删除购物车商品
    async removeFromCart(goodsId) {
      try {
        this.cartList = this.cartList.filter(item => item.cgId !== goodsId);
        this.updateCartSummary();
        const res = await service.delete(`/cart-goods/delete/${goodsId}`);
        if (res.code === 200) {
          ElMessage({
            message: '删除成功',
            type: 'info'
          })
        }
      } catch (error) {
        console.error('Failed to delete cartList:', error);
      }

    },

    //更新购物车总价和商品个数
    updateCartSummary() {
      this.totalQuantity = this.cartList.reduce((total, item) => total + item.cgNum, 0);
      this.totalPrice = this.cartList.reduce((total, item) => total + item.cgPrice, 0);
    },

    //退出后清空购物车
    clearCart() {
      this.cartList = [];
      this.updateCartSummary();
    },

    //用户手动清空购物车
    async handleClearCart(userId) {
      try {
        const res = await service.delete(`/cart-goods/delete-all/${userId}`);
        if (res.code === 200) {
          ElMessage({
            message: '已清空购物车',
            type: 'success'
          })
        }
        this.getCartList(userId)

      } catch (error) {
        console.error('Failed to clear cartList:', error);
      }
    }
  }
});
